package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Homework7Application {

	public static void main(String[] args) {
		SpringApplication.run(Homework7Application.class, args);
	}

}
import org.aspectj.lang.ProceedingJoinPoint;
		import org.aspectj.lang.annotation.*;
		import org.springframework.stereotype.Component;

@Aspect
@Component
public class ApiMonitorAspect {
	private Map<String, Integer> apiCallCountMap = new HashMap<>();
	private Map<String, Long> apiTotalTimeMap = new HashMap<>();
	private Map<String, Long> apiMaxTimeMap = new HashMap<>();
	private Map<String, Long> apiMinTimeMap = new HashMap<>();
	private Map<String, Integer> apiExceptionCountMap = new HashMap<>();

	@Pointcut("execution(* com.example.api.*.*(..))")
	public void apiMethods() {
	}

	@Around("apiMethods()")
	public Object monitorApi(ProceedingJoinPoint joinPoint) throws Throwable {
		String apiName = joinPoint.getSignature().toShortString();
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();

		try {
			// 执行目标方法
			Object result = joinPoint.proceed();
			return result;
		} catch (Exception e) {
			// 统计异常次数
			incrementExceptionCount(apiName);
			throw e;
		} finally {
			stopWatch.stop();
			long elapsedTime = stopWatch.getTotalTimeMillis();

			// 统计调用次数
			incrementCallCount(apiName);

			// 统计响应时间
			updateTotalTime(apiName, elapsedTime);
			updateMaxTime(apiName, elapsedTime);
			updateMinTime(apiName, elapsedTime);
		}
	}

	private void incrementCallCount(String apiName) {
		int count = apiCallCountMap.getOrDefault(apiName, 0);
		apiCallCountMap.put(apiName, count + 1);
	}

	private void incrementExceptionCount(String apiName) {
		int count = apiExceptionCountMap.getOrDefault(apiName, 0);
		apiExceptionCountMap.put(apiName, count + 1);
	}

	private void updateTotalTime(String apiName, long elapsedTime) {
		long totalTime = apiTotalTimeMap.getOrDefault(apiName, 0L);
		totalTime += elapsedTime;
		apiTotalTimeMap.put(apiName, totalTime);
	}

	private void updateMaxTime(String apiName, long elapsedTime) {
		long maxTime = apiMaxTimeMap.getOrDefault(apiName, Long.MIN_VALUE);
		if (elapsedTime > maxTime) {
			apiMaxTimeMap.put(apiName, elapsedTime);
		}
	}

	private void updateMinTime(String apiName, long elapsedTime) {
		long minTime = apiMinTimeMap.getOrDefault(apiName, Long.MAX_VALUE);
		if (elapsedTime < minTime) {
			apiMinTimeMap.put(apiName, elapsedTime);
		}
	}

	// 可以根据需要添加其他统计方法

	// Getter方法...
}